<template>
  <div :id="id" style="height:100%;width:100%;"></div>
</template>

<script>
  import echarts from 'echarts'

  let listData = [
    {value: 100, name: '100%'},
    {value: 0, name: ''}
  ]
  export default {
    name: '',
    data () {
      return {
        chart: null
      }
    },
    props: {
      textColor: {
        type: String,
        default: () => {
          return '#000'
        }
      },
      charData: {
        default: () => {
          return listData
        }
      },
      id: String
    },
    beforeUpdate: function () {
      this.drawPie(this.id)
    },
    watch: {
      charData: {
        immediate: true,
        handler(val, oldVal) {    // 监听charData，当放生变化时，触发这个回调函数绘制图表
          console.log('new: %s, old: %s', val, oldVal)
          let seriesData
          if (val && Array.isArray(val)) {
            listData = val
            seriesData = val
            this.drawPie(this.id)
            return val
          }
          let otherVal = 100 - val
          console.log(otherVal)
          seriesData = [
            {
              value: val, name: val + '%',
              label: {
                show: true,
                fontSize: '16',
                color: this.textColor,
                fontWeight: 'bold',
                position: 'center'
              }
            },
            {value: otherVal, name: ''}
          ]
          this.$nextTick(() => {
            this.drawPie(this.id, seriesData)
          })
        }
      }
    },
    methods: {
      drawPie (id, data) {
        if (!data) {
          return
        }
        this.charts = echarts.init(document.getElementById(id))
        let _data = {
          series: [
            {
              type: 'pie',
              color: [this.textColor, '#E2E2E2'],
              radius: ['70%', '90%'],
              selectedMode: false,
              labelLine: {
                show: false
              },
              emphasis: {
                label: {
                  show: false,
                  fontSize: '60',
                  fontWeight: 'bold'
                }
              },
              data: data || listData
            }
          ]
        }
        this.charts.setOption(_data)
      }
    },
    mounted() {
      this.$nextTick(() => {
        this.drawPie(this.id)
      })
    }
  }
</script>

<style scoped lang="">

</style>
